<?php
namespace App\Services\Chanjet;

use App\Http\Controllers\Chanjet\TplusCommonController;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use League\Flysystem\Exception;
use GuzzleHttp\Client;

class ChanjetRequest
{
    private $noNeedToken = ['authCodeExchangeToken','refreshToken'];
    private static $instance = null;

    private function __construct(){}
    private function __clone(){}
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function requestApi($methodName,$arguments)
    {
        $headers = $this->commonParam($methodName,$arguments);
//        var_dump($headers);die;
        //获取api参数
        $apiInfo = TPlusInterface::$methodName();

        $apiRequestUrl = env('CHANJET_URL').$apiInfo['url'];
        $apiRequestType = $apiInfo['type'];

        if(empty($apiRequestUrl) || empty($apiRequestType))
        {
            return "api请求配置异常, url: " .$apiRequestUrl .", type: ".$apiInfo['type'];
        }
        /**
         * 检测请求参数 必传 $arguments[0] 请求参数 $arguments[1] org_id
         *
        */
        //请求前
        //LogFormatRecord::record($apiRequestUrl,$apiRequestType,$arguments);
        if(isset($arguments[1]) && !empty($arguments[1])){
            if($apiRequestType == 'get'){
                $response = $this->curlGet($apiRequestUrl,$headers,$arguments[0]);
            }

            if($apiRequestType == 'post'){
                $response = $this->curlPost($apiRequestUrl,$headers,json_encode($arguments[0]));
            }
        }else{
            $response = ['code'=>'001','msg'=>'org_id not empty'];
        }

        $response = json_decode($response,true);
        //请求结果解密

        //请求后
        LogFormatRecord::record($apiRequestUrl,$apiRequestType,$arguments[0],$response);

        return $response;
    }
    /*
     *  公共参数
     *
     */
    public function commonParam($methodName,$arguments)
    {
        $headers = [
            'appKey' => env('CHANJET_APP_KEY'),
            'appSecret' => env('CHANJET_APP_SECRET'),
            'Content-Type' => 'application/json',
        ];

        if(!in_array($methodName,$this->noNeedToken))
        {
            if(isset($arguments[1])){
                //获取 org_id token
                if(isset($arguments[2]) && !empty($arguments[2])){
                    $TplusToken = $arguments[2];
                }else{
                    $TplusCommon = new TplusCommonController();
                    $TplusToken = $TplusCommon->getTplusToken($arguments[1]);
                }
                if(!empty($TplusToken)){
                    $headers['openToken'] = $TplusToken;
                }
            }
        }
        $new_heads = [];
        foreach ($headers as $key=>$item){
            $new_heads[] = $key.':'.$item;
        }
        //dump($new_heads);die;
        return $new_heads;
    }
    /**
     *  获取畅捷通T+系统token
     *  畅捷通T+ 数据表查询 token、express、刷新token
     *
    */
    public function __call($methodName, $arguments)
    {
        if($methodName == 'refreshToken'){
            //var_dump($methodName);var_dump($arguments);die;
        }
        //var_dump($arguments);die;
        return $this->requestApi($methodName,$arguments);
    }

    public function curlPost($url='',$headers=[],$data=[],$timeout=300){
//        var_dump($url);
//        dump($headers);
//        var_dump($data);die;
        //Log::info(json_encode($headers));

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch);
        curl_close($ch);
        //dump(curl_error($ch));die;
//        if (curl_errno($ch) !== null) {
//            return 'cURL Error: ' . curl_error($ch);
//        } else {
            // 处理响应结果
            return $response;
//        }
    }
    public function curlGet($url='',$headers=[],$data=[],$timeout=300){
        $ch = curl_init();
        $url = $url.'?'.http_build_query($data);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        curl_close($ch);
//        if (curl_errno($ch)) {
//            return 'cURL Error: ' . curl_error($ch);
//        } else {
            // 处理响应结果
            return $response;
//        }

    }

}

?>
